import { useState, useEffect, useRef } from "react";
import QuestionList from "./QuestionList";
import Pagination from "../../libs/Pagination";
import { getQuestionApi } from "../../http/module/Question";

export default function QuestionsPage() {
  const [questions, setQuestions] = useState([]);
  const [pagination, setPagination] = useState({
    currentPage: 1,
    totalPages: 1,
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const abortControllerRef = useRef(new AbortController());
  const expectedPageRef = useRef(1);

  const fetchQuestions = async (page) => {
    expectedPageRef.current = page;
    try {
      abortControllerRef.current.abort();
      abortControllerRef.current = new AbortController();

      setLoading(true);
      const response = await getQuestionApi(page, {
        signal: abortControllerRef.current.signal,
      });

      // 仅处理有效响应
      if (page === expectedPageRef.current) {
        setQuestions(response.data.records);
        setPagination((prev) => ({
          ...prev,
          totalPages: response.data.totalPage,
        }));
      }
    } catch (err) {
      if (err.name !== "AbortError") {
        setError(err.message || "获取数据失败");
      }
    } finally {
      if (page === expectedPageRef.current) {
        setLoading(false);
      }
    }
  };

  useEffect(() => {
    const currentPage = pagination.currentPage;
    fetchQuestions(currentPage);

    return () => abortControllerRef.current.abort();
  }, [pagination.currentPage]);

  const handlePageChange = (newPage) => {
    if (newPage === pagination.currentPage) return;
    setPagination((prev) => ({ ...prev, currentPage: newPage }));
  };

  if (error) {
    return <div className="text-red-500 p-4">错误：{error}</div>;
  }

  return (
    <div className="max-w-5xl mx-auto p-6">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold">最新问题</h1>
      </div>

      {loading ? (
        <div className="text-center py-8">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
        </div>
      ) : (
        <>
          <QuestionList questions={questions} />
          <div className="mt-6">
            <Pagination
              currentPage={pagination.currentPage}
              totalPages={pagination.totalPages}
              onPageChange={handlePageChange}
            />
          </div>
        </>
      )}
    </div>
  );
}
